import { _decorator, Component, Widget, sys, view, UITransform } from 'cc';
import { EDITOR } from 'cc/env';
const { ccclass, requireComponent, executeInEditMode } = _decorator;

@ccclass('SafeArea')
@requireComponent([Widget, UITransform])
@executeInEditMode(true)
export class SafeArea extends Component {
    protected onLoad(): void {
        if (EDITOR) {
            const widget = this.node.getComponent(Widget);
            widget.isAlignTop = true;
            widget.isAlignBottom = true;
            widget.isAlignLeft = true;
            widget.isAlignRight = true;
            widget.top = 0;
            widget.bottom = 0;
            widget.left = 0;
            widget.right = 0;
            widget.updateAlignment();
            return;
        }

        let topGap = 0;
        const safeArea = sys.getSafeAreaRect();
        if (sys.platform === sys.Platform.WECHAT_GAME) {
            try {
                //@ts-ignore
                const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
                //@ts-ignore
                // const windowInfo = wx.getWindowInfo();
                // console.log('微信设备信息  safeArea', windowInfo.safeArea);
                console.log('微信设备信息  menuButtonInfo', menuButtonInfo);
                const menuBtnHeight = menuButtonInfo.height + menuButtonInfo.top;
                topGap = view.getVisibleSize().height - safeArea.y - safeArea.height + menuBtnHeight;
            } catch (error) {
                console.log('微信设备信息  ', error);
                topGap = view.getVisibleSize().height - safeArea.y - safeArea.height + 80;
            }
        } else {
            topGap = view.getVisibleSize().height - safeArea.y - safeArea.height;
        }

        const topWidget = this.node.getComponent(Widget);
        if (topWidget) {
            // topWidget.alignMode = Widget.AlignMode.ALWAYS;
            topWidget.top = topGap;
            topWidget.updateAlignment();
            console.log('顶部适配信息  ', topWidget.top);
        } else {
            const oldPos = this.node.position;
            this.node.setPosition(oldPos.x, oldPos.y - topGap, 0);
        }
    }
}